<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use \Illuminate\Database\Eloquent\Relations\BelongsTo;

class Agent extends Model
{
    public $table = 'agent';

    public $guarded = [];

    const MAX_RATE = 0.3;


    public $casts = [
        'created_at' => 'date:Y-m-d H:i:s'
    ];
//    public function shop() {
//        return $this->hasMany(Shop::class);
//    }
//
//    public function hasShop()
//    {
//        return $this->belongsToMany(Shop::class, 'agent_has_shop')->withPivot(['rate']);
//    }
    public function bank(){
        return $this->hasOne(AgentBank::class,'agent_id','id');
    }



    public function parent()
    {
        // 假设每个Agent有一个pid字段指向它的父代理
        return $this->belongsTo(Agent::class, 'pid', 'id');
    }

    public function business(){
        return $this->hasMany(Business::class);
    }

    public function device(){
        return $this->hasMany(Device::class);
    }

    public function cashLog()
    {
        return $this->hasMany(AgentCashLog::class);
    }

    public function amountLog()
    {
        return $this->hasMany(AgentAmountLog::class);
    }


    public static function getAllCategories($stop_id=0){
        $data = Agent::query()->whereNull('deleted_at')
            ->orderBy('sort','desc')
            ->orderBy('id','desc')->get(['id','name','rate','mobile','avatar','pid','service','type']);
        return self::noLimitCategory( $data,0,0,$stop_id);
    }

    public static function noLimitCategory($categories,$parent_id=0,$level=0,$stop_id=0){
        //定义一个静态数组用于保存每次遍历的结果
        static $res= array();
        //遍历数组进行数据判断
        foreach($categories as $value){
            //判断数据的父级分类id
            if($value['pid']==$parent_id){
                //当分类的id不等于自己的id时进行遍历
                if($value['id']!=$stop_id){
                    $value['level']=$level;
                    $res[]=$value;
                    //递归点：当前分类有可能有子分类
                    self::noLimitCategory($categories,$value['id'],$level+1,$stop_id);
                }
            }
        }
        //返回最终的结果
        return $res;
    }


}
